

{% set BASE_NAME = properties['baseName'] + '-' + env['name'] %}
{% set REGION = properties['zone'][:-2] %}
{% set TEAMCITY_DB = 'teamcitydb' %}
{% set TEAMCITY_USER = 'teamcity' %}

{% if properties['size'] == 'large' %}
  {% set DB_TIER = 'db-n1-standard-2' %}
{% else %}
  {% set DB_TIER = 'db-n1-standard-1' %}
{% endif %}

resources:
- name: {{ BASE_NAME }}
  type: gcp-types/sqladmin-v1beta4:instances
  properties:
    region: {{ REGION }}
    settings:
      tier: {{ DB_TIER }}
      backupConfiguration:
        binaryLogEnabled: true
        enabled: true
      databaseFlags:
      - name: long_query_time
        value: 5
      - name: slow_query_log
        value: 1
      - name: character_set_server
        value: utf8
      - name: max_allowed_packet
        value: 16777216

- name: create-user
  type: gcp-types/sqladmin-v1beta4:users
  metadata:
    dependsOn:
    - {{ BASE_NAME }}
  properties:
    name: {{ TEAMCITY_USER }}
    instance: $(ref.{{ BASE_NAME }}.name)
    host: "cloudsqlproxy~%"

- name: create-database
  type: gcp-types/sqladmin-v1beta4:databases
  metadata:
    dependsOn:
    - create-user
  properties:
    name: {{ TEAMCITY_DB }}
    instance: $(ref.{{ BASE_NAME }}.name)
    charset: utf8

- name: delete-root-user
  action: gcp-types/sqladmin-v1beta4:sql.users.delete
  metadata:
    runtimePolicy:
    - CREATE
    dependsOn:
    - create-database
  properties:
    name: root
    instance: $(ref.{{ BASE_NAME }}.name)
    host: "%"

outputs:
- name: instance
  value: $(ref.{{ BASE_NAME }}.name)
- name: name
  value: $(ref.create-database.name)
- name: user
  value: {{ TEAMCITY_USER }}
